﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using mediaPrime.Sdk;

namespace mediaPrime.Plugin.SystemManagement
{
    public class SystemPlugin : mediaPrime.Sdk.Plugin, INotifyPropertyChanged
    {
        internal static SystemPlugin Instance;

        private MainUserControl mainUserControl;
        private TileContent tileContent;
        private string mediaprimeversion;

        public string mediaPrimeVersion
        {
            get { return mediaprimeversion; }
            set
            {
                if (value != mediaprimeversion)
                {
                    mediaprimeversion = value;
                    onPropertyChanged("mediaPrimeVersion");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public ObservableCollection<ExtensionInfo> AvailablePlugins { get; set; }

        public SystemPlugin()
        {
            Instance = this;

            this.QueryResult += SystemPlugin_QueryResult;

            SendQuery(QueryTypes.AvailablePlugins);
        }

        private void SystemPlugin_QueryResult(object sender, QueryResultEventArgs e)
        {
            if (e.Exception != null)
            {
                Logger.Log.Error(e.Exception.ToString());
            }

            if (e.Type == QueryTypes.mediaPrimeVersion)
                mediaPrimeVersion = (e.Result as Version).ToString(3);
            else if (e.Type == QueryTypes.AvailablePlugins)
                AvailablePlugins = e.Result as ObservableCollection<ExtensionInfo>;
        }

        private void onPropertyChanged(string property)
        {
            var propertyChanged = PropertyChanged;
            if (propertyChanged != null)
                propertyChanged(this, new PropertyChangedEventArgs(property));
        }

        private void initializeUserInterface()
        {
            SendQuery(QueryTypes.mediaPrimeVersion);

            mainUserControl = new MainUserControl(this);
        }

        public override UIElement GetUserInterface()
        {
            if (mainUserControl == null)
                initializeUserInterface();

            return mainUserControl;
        }

        public override UIElement GetTileContent()
        {
            if (tileContent == null)
                tileContent = new TileContent();

            return tileContent;
        }



    }
}
